<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<%@page import="java.util.*"%>

<% 
	//List<Location> locations = (ArrayList<Location>) request.getAttribute("locations");
	String latLng = (String) request.getAttribute("latLng");
	String strategy = (String) request.getAttribute("strategy");
	String avoidTolls = (String) request.getAttribute("avoidTolls");
%>

<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Intelligent Route for Carrier</title>
<link rel="icon" type="image/gif" href="./resources/images/animated_favicon1.gif">
	<!-- link rel="shortcut icon" href="favicon.ico" -->
	
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="./resources/tileoverlay_uncompressed.js"></script>
<script type="text/javascript" src="./resources/googleAPI.js"></script>
<script type="text/javascript" src="./resources/traffyAPI.js"></script>
<script type="text/javascript" src="./resources/jquery.js"></script>

<style type="text/css">
html {
  height: 100%;
}

body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#map_canvas {
  height: 100%;
  position: absolute;
  bottom:0;
  left:0;
  right:0;
  top:0;
  border-right:3px solid #555555;
  margin-right: 30%;
}


#directionsPanelMain {
	height: 100%;
	float: right;
	width: 29%;
	overflow: scroll;
  	position: absolute;
  	margin-left: 71%;
}
</style>

<title>Schedule On Map</title>
<script type="text/javascript">
var comingRainMin = 0;
var comingRainSec = 0;
function createXMLHttpRequest(){
  // See http://en.wikipedia.org/wiki/XMLHttpRequest
  // Provide the XMLHttpRequest class for IE 5.x-6.x:
  if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
    throw new Error( "This browser does not support XMLHttpRequest.")
  };
  return new XMLHttpRequest();
}

var directionsService = new google.maps.DirectionsService();
	function getLinks() {
		var url = getLinkIdUrl;
		var script = document.createElement('script');
		script.setAttribute('src', url);
		document.getElementsByTagName('head')[0].appendChild(script);
	}
	
	function init() {
		if('<%=latLng%>'!='null'){
			getLocation('<%=latLng%>');
		}
		//getLinks();
		// GET INCIDENTS
		getIncidents();
		
		// GET VMS
		getVMS();

		// GET CCTV
		getCCTV();
		
		
	}	

	var bestRoute = "";
	var currentRoute = "";
	var shortest = "";
	function computeTotalDistance(result) {
	  document.getElementById("originalTime").innerHTML = "";
	  var total = 0;
	  var duration = 0;
	  var myroute = result.routes[0];
	  for (i in myroute.legs) {
	  	total += myroute.legs[i].distance.value;
	  	duration += myroute.legs[i].duration.value;

	  }
	  total = total / 1000.;
	  duration = duration / 60.;
	  $("#total").html(total + " km").hide().fadeIn(1500);
	  $("#duration").html(Math.round(duration*100)/100 + " mins").hide().fadeIn(1500); // This is for 2 digits -- Math.ceil(duration);
	  $("#directionsPanel").hide().fadeIn(1500);
	  currentRoute = result;
	}  
	
	var ajaxLoader = document.createElement('DIV');
	function findRelatedTraffic(result){
		//Show loader
		var withOutTrafic = document.getElementById("duration").innerHTML;
		withOutTrafic = withOutTrafic.substring(0,withOutTrafic.length-5);
		document.getElementById("duration").innerHTML = "";
		document.getElementById("originalTime").innerHTML = "";
		loaderImg = new Image();
		loaderImg.src = "./resources/images/ajax-loader4.gif";
		document.getElementById("duration").appendChild(loaderImg);
		//ajaxLoader.style.display = "inline";
		
		var request = createXMLHttpRequest();
		var links = "";
		var duration = 0;
		for (i in result.routes[0].legs) {
			var legObj = result.routes[0].legs[i];
			for (j in legObj.steps) {
				if(j==0){
					request.open('get','./AJAX?todo=getLinkId&location='+legObj.steps[j].start_location,false);
					request.send(null);
				}else{
					request.open('get','./AJAX?todo=getLinkId&location='+legObj.steps[j].end_location,false);
					request.send(null);
				}
				
				var txt = request.responseText;
				if(txt != 0){
					links+=","+txt; // May change to sent all links in one time to reduce the traffic of network
					request.open('get','./AJAX?todo=getCL&link='+txt,false);
					request.send(null);
					var cl = request.responseText;
					if(cl!=""){
						var cls = cl.split("##");
						var meanOfeachLeg = 0 ;
						for(index in cls){
							if(cls[index] == "H"){
								meanOfeachLeg += legObj.steps[j].duration.value * 3;
							}else if(cls[index] == "M"){
								meanOfeachLeg += legObj.steps[j].duration.value * 2;
							}else{// L
								meanOfeachLeg += legObj.steps[j].duration.value;
							}
						}
						meanOfeachLeg = meanOfeachLeg/cls.length;
						duration += meanOfeachLeg;
					}else{// L
						duration += legObj.steps[j].duration.value;
					}
				}else{
					duration += legObj.steps[j].duration.value;
				}
				
		    }
	    }
		duration = duration / 60.;
		//var previous = $("#duration").html().substring(0, $("#duration").html().length-5);
		if(bestRoute==""){
			bestRoute = currentRoute;
			shortest = Math.round(duration*100)/100;
			document.getElementById("getBest").style.border = "1px solid silver";
			document.getElementById("getBest").style.background = "#EEEEEE";
			document.getElementById("getBest").style.padding = "3px";
			document.getElementById("getBest").style.marginTop = "5px";
			$("#getBest").html("Based on traffic, now the best is: "+shortest).slideUp(0).fadeIn(1500);
		}else if(duration < shortest){
			bestRoute = currentRoute;
			shortest = Math.round(duration*100)/100;
			$("#getBest").html("Based on traffic, now the best is: "+shortest).slideUp(0).fadeIn(1500);
		}
		$("#duration").html(Math.round(duration*100)/100 + " mins").slideUp(0).fadeIn(1500);
		$("#originalTime").html(", original is: "+withOutTrafic).slideUp(0).fadeIn(1500);
		
	}	

	function getLocation(obj){
		var getTraffic = "traffy"; //traffy or google
		
		var latLng = obj.split("##");
		
		var start;
		var end;
		var length = latLng.length;
		var loopBoundary;
		if(length != 0){
			var tempStart = latLng[0].substring(1, latLng[0].length-1);
			var tempEnd = latLng[length-1].substring(1, latLng[length-1].length-1);
			start = new google.maps.LatLng(tempStart.split(",")[0], tempStart.split(",")[1]);
			
			createMap(tempStart.split(",")[0], tempStart.split(",")[1], "map_canvas", getTraffic);
			
			if("<%=strategy%>" == "roundtrip"){
				end = start;
				loopBoundary = length;
			}else if("<%=strategy%>" == "oneway"){
				end = new google.maps.LatLng(tempEnd.split(",")[0], tempEnd.split(",")[1]);
				loopBoundary = length-1;
			}
		}else{
			createMap(13.711428, 100.594103, "map_canvas", getTraffic);
		}
		
		directionsDisplay.setPanel(document.getElementById("directionsPanel"));

		google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
		    computeTotalDistance(directionsDisplay.directions);
		    //findRelatedTraffic(directionsDisplay.directions);
		});

		var waypts = [];
		for( var i=1; i<loopBoundary; i++){
			var tempLocation = latLng[i].substring(1, latLng[i].length-1);
			var wayPoint = new google.maps.LatLng(tempLocation.split(",")[0], tempLocation.split(",")[1]);
			waypts.push({
	          	location:wayPoint,
	          	stopover:true
      		});
		}
		var avoidToll = "<%=avoidTolls%>";
		if(avoidToll == "yes"){
			avoidToll = true;
	    }else{
	    	avoidToll = false;
	    }
	    
		var req = {
			   	origin:start, 
			    destination:end,
			    waypoints: waypts,
			    optimizeWaypoints: true,
			    avoidTolls: avoidToll,
			    travelMode: google.maps.DirectionsTravelMode.DRIVING,
			    region: 'th',
			    provideRouteAlternatives: false //It can use just in case that there is no waypoint
			};
			directionsService.route(req, function(result, status) {
				if (status == google.maps.DirectionsStatus.OK) {
				    directionsDisplay.setDirections(result);
				    var myroute = result.routes[0];
				}else{
					alert(status);
				}
			});
		
		// Create the DIV to enable/disable GPS function
		var locationControlDiv = document.createElement('DIV');
		var locationControl = new LocationControl(locationControlDiv, map);

	 	locationControlDiv.index = 1;
		map.controls[google.maps.ControlPosition.TOP_RIGHT].push(locationControlDiv);
		
		//Create the DIV to recalculate duration based on traffy
		var durationControlDiv = document.createElement('DIV');
		var durationControl = new DurationControl(durationControlDiv, map);

		durationControlDiv.index = 2;
		map.controls[google.maps.ControlPosition.TOP_RIGHT].push(durationControlDiv);
		
		//Create the DIV to recalculate duration based on traffy
		var loaderControl = new LoaderControl(ajaxLoader, map);

		ajaxLoader.index = 3;
		map.controls[google.maps.ControlPosition.RIGHT_TOP].push(ajaxLoader);

		//Create the DIV to for getting rain forecast
		var rainControlDiv = document.createElement('DIV');
		var rainControl = new RainControl(rainControlDiv, map);

		rainControlDiv.index = 4;
		map.controls[google.maps.ControlPosition.TOP_RIGHT].push(rainControlDiv);
	}
	
	function RainControl(controlDiv, map) {

	  // Set CSS styles for the DIV containing the control
	  // Setting padding to 5 px will offset the control
	  // from the edge of the map
	  controlDiv.style.padding = '5px';

	  // Set CSS for the control border
	  var uiControl = document.createElement('DIV');
	  uiControl.style.padding = '3px';
	  uiControl.style.backgroundColor = '#FFFFFF';
	  uiControl.style.borderStyle = 'solid';
	  uiControl.style.borderWidth = '2px';
	  uiControl.style.borderColor = '#B9C6EF';
	  uiControl.style.cursor = 'pointer';
	  uiControl.style.textAlign = 'center';
	  uiControl.title = 'Click to get rain forecast';
	  controlDiv.appendChild(uiControl);

	  // Set CSS for the control interior
	  var textControl = document.createElement('DIV');
	  textControl.style.fontFamily = 'Arial,sans-serif';
	  textControl.style.fontSize = '12px';
	  textControl.innerHTML = 'Rain Forecast';
	  textControl.id = "rainButton";
	  uiControl.appendChild(textControl);

	  // Setup the click event listeners: simply set the map to Chicago
	  google.maps.event.addDomListener(uiControl, 'click', function() {
		  getRainForecast(directionsDisplay.directions);
	  });
	}

	function getRainForecast(result){
		window.clearTimeout(t2); 
		comingRainMin = 30;
		comingRainSec = 01;
		//document.getElementById("loader").style.display = "inline";
		//document.getElementById("closeRainImg").style.display = "inline";
		document.getElementById("rainContainer").style.border = "1px solid silver";
		document.getElementById("rainContainer").style.background = "#EEEEEE";
		document.getElementById("rainContainer").style.padding = "5px";
		
		$("#rainDetail").html("");
		$("#rainDetail").append("<b><span id='rainTime'></span></b><br><br>");
		
		loaderImg = new Image();
		loaderImg.src = "./resources/images/ajax-loader.gif";
		loaderImg.id = "rainLoader";
		document.getElementById("loaderContainer").appendChild(loaderImg);
		
		countDown();
		var request = createXMLHttpRequest();
		var txt="";
		var noRain = true;
		for (i in result.routes[0].legs) {
			var legObj = result.routes[0].legs[i];
			if(i==0){// only first leg
				request.open('get','./AJAX?todo=getRainForecast&location='+legObj.start_location,false);
				request.send(null);
				txt = request.responseText;
				if(txt!="0"){
					noRain = false;
					if(txt=="1"){
						$("#rainDetail").append("<i>"+legObj.start_address+": <b>little rain</b></i><br><br>");
					}else if(txt=="2"){
						$("#rainDetail").append("<i>"+legObj.start_address+": <b>medium rain</b></i><br><br>");
					}else if(txt=="3"){
						$("#rainDetail").append("<i>"+legObj.start_address+": <b>heavy rain</b></i><br><br>");
					}else if(txt=="4"){
						$("#rainDetail").append("<i>"+legObj.start_address+": <b>very heavy rain</b></i><br><br>");
					}
				}
				else{
					$("#rainDetail").append("<i>"+legObj.start_address+": <b>no rain</b></i><br><br>");
				}
			}

			request.open('get','./AJAX?todo=getRainForecast&location='+legObj.end_location,false);
			request.send(null);
			txt = request.responseText;
			if(txt!="0"){
				noRain = false;
				if(txt=="1"){
					$("#rainDetail").append("<i>"+legObj.end_address+": <b>little rain</b></i><br><br>");
				}else if(txt=="2"){
					$("#rainDetail").append("<i>"+legObj.end_address+": <b>medium rain</b></i><br><br>");
				}else if(txt=="3"){
					$("#rainDetail").append("<i>"+legObj.end_address+": <b>heavy rain</b></i><br><br>");
				}else if(txt=="4"){
					$("#rainDetail").append("<i>"+legObj.end_address+": <b>very heavy rain</b></i><br><br>");
				}
			}
			else{
				$("#rainDetail").append("<i>"+legObj.end_address+": <b>no rain</b></i><br><br>");
			}
	    }
	    if(noRain){
	    	//document.getElementById("rainDetail").innerHTML = "<i>There is no rain  :)</i>";
	    }
		//document.getElementById("loader").style.display = "none";
		$("#rainDetail").hide().fadeIn(1500);
	    document.getElementById("loaderContainer").removeChild(document.getElementById("rainLoader"));
	}
	
	function LoaderControl(controlDiv, map) {
		loaderImg = new Image();
		loaderImg.src = "./resources/images/ajax-loader.gif";
		controlDiv.appendChild(loaderImg);
		controlDiv.style.padding = '5px';
		ajaxLoader.style.display = "none";
	}
	
	function DurationControl(controlDiv, map) {

	  // Set CSS styles for the DIV containing the control
	  // Setting padding to 5 px will offset the control
	  // from the edge of the map
	  controlDiv.style.padding = '5px';

	  // Set CSS for the control border
	  var uiControl = document.createElement('DIV');
	  uiControl.style.padding = '3px';
	  uiControl.style.backgroundColor = '#FFFFFF';
	  uiControl.style.borderStyle = 'solid';
	  uiControl.style.borderWidth = '2px';
	  uiControl.style.borderColor = '#B9C6EF';
	  uiControl.style.cursor = 'pointer';
	  uiControl.style.textAlign = 'center';
	  uiControl.title = 'Click to calculate traffic time';
	  controlDiv.appendChild(uiControl);

	  // Set CSS for the control interior
	  var textControl = document.createElement('DIV');
	  textControl.style.fontFamily = 'Arial,sans-serif';
	  textControl.style.fontSize = '12px';
	  textControl.innerHTML = 'Traffic Time';
	  uiControl.appendChild(textControl);

	  // Setup the click event listeners: simply set the map to Chicago
	  google.maps.event.addDomListener(uiControl, 'click', function() {
		  findRelatedTraffic(directionsDisplay.directions);
	  });
	}
	
	var controlUI = document.createElement('DIV');
	function LocationControl(controlDiv, map) {

	  // Set CSS styles for the DIV containing the control
	  // Setting padding to 5 px will offset the control
	  // from the edge of the map
	  controlDiv.style.padding = '5px';

	  // Set CSS for the control border
	  controlUI.style.padding = '3px';
	  controlUI.style.backgroundColor = '#FFFFFF';
	  controlUI.style.borderStyle = 'solid';
	  controlUI.style.borderWidth = '2px';
	  controlUI.style.borderColor = '#B9C6EF';
	  controlUI.style.cursor = 'pointer';
	  controlUI.style.textAlign = 'center';
	  controlUI.title = 'Click to enable GPS';
	  controlDiv.appendChild(controlUI);

	  // Set CSS for the control interior
	  var controlText = document.createElement('DIV');
	  controlText.style.fontFamily = 'Arial,sans-serif';
	  controlText.style.fontSize = '12px';
	  controlText.innerHTML = 'Enable GPS';
	  controlUI.appendChild(controlText);

	  // Setup the click event listeners: simply set the map to Chicago
	  google.maps.event.addDomListener(controlUI, 'click', function() {
		  setGPSStatus();
	  });
	}
	
	var message = "";
	var t;
	function getCurrentLocationLoop(){
		controlUI.innerHTML = "";
	  	var controlText = document.createElement('DIV');
	  	controlText.style.fontFamily = 'Arial,sans-serif';
	  	controlText.style.fontSize = '12px';
	  	controlText.id = "gpsButton";
		if(message=="enable"){
		  controlText.innerHTML = 'Disable GPS';
		  controlUI.title = 'Click to disable GPS';
		  controlUI.appendChild(controlText);
		  $("#gpsButton").hide().fadeIn(1500);
		  getCurrentLocation();
		  t=setTimeout("getCurrentLocationLoop()",60000); // every minute;
		}else{
			clearCurrentLocation();
			clearTimeout(t);
			controlText.innerHTML = 'Enable GPS';
			controlUI.title = 'Click to enable GPS';
			controlUI.appendChild(controlText);
			$("#gpsButton").hide().fadeIn(1500);
		}
	}
	
	function setGPSStatus(){
		if(message==""){
			message = "enable";
		}else if(message=="enable"){
			message = "disable";
		}else if(message=="disable"){
			message = "enable";
		}
		getCurrentLocationLoop();
	}

	function hideDiv(id){
		document.getElementById(id).style.display = "none";
	}

	var t2;
	function countDown(){
		comingRainSec--;
		var time;
		  if (comingRainSec == -01) {
			  comingRainSec = 59;
			  comingRainMin = comingRainMin - 1;
		  } else {
			  comingRainMin = comingRainMin;
		  }
		if (comingRainSec<=9) { comingRainSec = "0" + comingRainSec; }
		  time = (comingRainMin<=9 ? "0" + comingRainMin : comingRainMin) + ":" + comingRainSec + " minutes ... ";
		if (document.getElementById) { document.getElementById("rainTime").innerHTML = "In next "+time; }
		  t2=window.setTimeout("countDown();", 1000);
		if (comingRainMin == '00' && comingRainSec == '00') { 
			$("#rainTime").html("Now...").hide().fadeIn(1500);
			comingRainSec = "00"; window.clearTimeout(t2); 
		}
	}

	function getTheBestRoute(){
		directionsDisplay.setDirections(bestRoute);
	}
</script>
</head>
<body onload="init()">
	<div id="printPanel">
		<div id="map_canvas" ></div> 
		<div id="directionsPanelMain">
			<a href="javascript:getTheBestRoute();" id="getBest"></a>
			<p>Total Distance: <span id="total"></span><br/>
				Total Duration: <span id="duration"></span> <i><span id="originalTime" style="color: gray;"></span></i>
			</p> 
			<div id="rainContainer"><span id="rainDetail"></span><span id="loaderContainer"></span></div>
			<div id="directionsPanel"></div>
		</div>
	</div>
</body>
</html>